
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-row>
            <el-col :span="5">
              <el-form-item label="订单状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
                  <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="适用地区" prop="province">
                <el-select
                  v-model="queryParams.province"
                  placeholder="请选择"
                  clearable
                  size="small"
                  remote
                  filterable
                  :remote-method="remoteMethod"
                  :loading="selectload"
                >
                  <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="订单编号" prop="order_number">
                <el-input
                  v-model="queryParams.order_number"
                  placeholder="请输入标题"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="9" class="itemStyle">
              <el-form-item label="提交时间">
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="queryParams.phone"
                  placeholder="请输入标题"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="课程名称" prop="course_name">
                <el-input
                  v-model="queryParams.course_name"
                  placeholder="请输入标题"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="复审人员" prop="recheck_user_id">
                <el-select v-model="queryParams.recheck_user_id" filterable placeholder="请选择复审人">
                  <el-option
                    v-for="item in userArray"
                    :key="item.user_id"
                    :label="item.nick_name"
                    :value="item.user_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-form-item style="float:right">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
        </el-form>

        <el-button class="mb10" type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <div style="display: flex">
          <div style="margin-right: 10px">订单总数：{{ total }}</div>
          <div>订单总金额：{{ $Prices(sum) }}（元）</div>
        </div>
        <el-table
          v-loading="loading"
          :data="sysOrderList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" header-align="center" width="50" label="序号" fixed="left" align="center" />
          <el-table-column header-align="center" :show-overflow-tooltip="true" label="订单编号" fixed="left">
            <template slot-scope="scope">
              <span>{{ scope.row.order_number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单名称" header-align="center" align="left" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.Course[0] ? scope.row.Course[0].name : '-' }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column header-align="center" prop="subject" label="科目" />
          <el-table-column header-align="center" prop="province" label="适用地区" />-->
          <el-table-column label="订单金额" header-align="center" align="left" prop="price" width="100">
            <template slot-scope="scope">
              <span class="text-price">{{ $Prices(scope.row.price) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单返佣" header-align="center" align="left" prop="commission" width="100">
            <template slot-scope="scope">
              <span class="text-price">{{ $Prices(scope.row.commission) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="customer" label="关联上级" header-align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.customer && scope.row.customer.recommenders && scope.row.customer.recommenders.name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" header-align="center" align="left" prop="status" width="100">
            <template slot-scope="scope">
              <el-tag :type="tagType(scope.row.status)">{{ tagStatus(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="复审人" header-align="center" align="left" prop="username">
            <template slot-scope="scope">
              <span>{{ scope.row.RecheckUser ? scope.row.RecheckUser.username : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="买家信息" header-align="center" align="left" prop="customer">
            <template slot-scope="scope">
              <span>{{ scope.row.customer ? scope.row.customer.name : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="买家号码"
            header-align="center"
            align="left"
            prop="customer"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.customer ? scope.row.customer.phone : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提交时间" align="center" prop="createdAt" width="155px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-user"
                :disabled="!(scope.row.status === 1)"
                @click="allocation(scope.row)"
              >分配</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="!(scope.row.status === 3)"
                @click="handleReview(scope.row)"
              >复审</el-button>
              <router-link
                :to="{ name: 'OrderView', params: { id: scope.row.id, type: 'offline' } }"
                style="margin-left: 6px"
              >
                <el-button size="mini" type="text" icon="el-icon-view">查看</el-button>
              </router-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>

      <el-drawer ref="drawer" title="订单复审" :visible.sync="open" direction="rtl" size="40%" custom-class="demo-drawer">
        <div class="info-body">
          <el-descriptions :column="2">
            <div slot="title" style="display: flex">
              <div style="margin-right: 20px">单号：{{ info.order_number ? info.order_number : '-' }}</div>
              <div>订单金额：{{ $Prices(info.price) }}</div>
            </div>
            <el-descriptions-item label="实收金额">{{ $Prices(info.actual_income) }}</el-descriptions-item>
            <el-descriptions-item label="购买人">{{ info.customer ? info.customer.name : '' }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="tagType(info.status)" size="small">{{ tagStatus(info.status) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="购买课程">{{ subjectName }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ info.createdAt && parseTime(info.createdAt) }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ info.customer ? info.customer.phone : '' }}</el-descriptions-item>
            <el-descriptions-item label="归属大区">{{ info.department ? info.department.Department.deptName : '' }}
            </el-descriptions-item>
            <el-descriptions-item label="所属区域">{{ province }}</el-descriptions-item>
            <el-descriptions-item label="归属教学点">{{ info.department ? info.department.name : '' }}</el-descriptions-item>
            <el-descriptions-item label="课程科目">{{ subject }}</el-descriptions-item>
            <el-descriptions-item label="关联上级">{{ !info.customer ? '' : info.customer.recommenders ?
              info.customer.recommenders.name : ''
            }}</el-descriptions-item>
            <el-descriptions-item v-if="info.sign_flow_id" label="电子合同下载">
              <div style="color: #409eff; cursor:pointer" @click="download">下载</div>
            </el-descriptions-item>
            <!-- <el-descriptions-item label="上级返佣">{{ info.subject }}</el-descriptions-item> -->
          </el-descriptions>
        </div>
        <el-form
          ref="form"
          :model="form"
          :rules="{
            recheck: [{ required: true, message: '复审意见不能为空', trigger: 'blur' }],
            recheck_ok: [{ required: true, message: '选择复审意见', trigger: 'blur' }],
          }"
          label-width="120px"
          style="margin-bottom: 16px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="复审是否通过" prop="recheck_ok">
                <el-select v-model="form.recheck_ok" style="width: 100%" placeholder="请选择" size="small">
                  <el-option v-for="dict in recheckList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="跟进意见" prop="follow_up">
                <el-input v-model="form.follow_up" type="textarea" :rows="2" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="合同编号" prop="contract_no">
                <el-input v-model="form.contract_no" type="textarea" :rows="2" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="复审意见" prop="recheck">
                <el-input v-model="form.recheck" type="textarea" :rows="3" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-drawer>
      <UserList :visible="visible" @cancelUser="cancelUser" @submitUser="submitUser" />
    </template>
  </BasicLayout>
</template>

<script>
import { offlineOrderList, assignOrder, fileDownloadUrl } from '@/api/admin/sys-order'
import { reviewOrder } from '@/api/admin/sys-finance'
import { offlineStatusOptions, getTagType, getStatus } from '../utils'
import { formatJson, prices } from '@/utils'
import { getCity, getUserList } from '@/api/admin/sys-course'
import { parseTime } from '@/utils/costum'
import UserList from '@/components/UserList'
export default {
  name: 'SysOrderReviewManage',
  components: {
    UserList
  },
  data() {
    return {
      statusOptions: offlineStatusOptions,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      sum: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      form: {},
      info: {},
      sysOrderList: [],
      dateRange: [],
      logisticsList: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        status: undefined,
        province: undefined,
        order_number: undefined,
        begin_time: undefined,
        end_time: undefined,
        phone: undefined,
        course_name: undefined,
        recheck_user_id: undefined
      },
      cityList: [],
      recheckList: [
        {
          label: '通过',
          value: 1
        },
        {
          label: '不通过',
          value: 2
        }
      ],
      selectload: false,
      visible: false,
      subjectName: '',
      subject: '',
      province: '',
      userArray: []
    }
  },
  created() {
    this.getList()
    getCity().then(res => {
      this.cityList = res?.data || []
    })
    getUserList().then(res => {
      this.userArray = res?.data
    })
  },
  methods: {
    download() {
      fileDownloadUrl(this?.info?.sign_flow_id).then(res => {
        const { data } = res
        window.location.href = data?.files?.[0].downloadUrl
      })
    },
    tagType(status) {
      return getTagType('offline', status)
    },
    tagStatus(status) {
      return getStatus('offline', status)
    },
    getList() {
      this.loading = true
      try {
        offlineOrderList(this.addDateRange(this.queryParams, this.dateRange))
          .then(response => {
            this.sysOrderList = response.data.list
            this.total = response.data.count
            this.sum = response.data.sum ?? 0
          })
          .finally(() => {
            this.loading = false
          })
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    parentIdFormat(row) {
      return this.selectItemsLabel(this.parentIdOptions, row.parentId)
    },
    // 文件
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consult_wz_id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleReview(row) {
      console.log(row)
      this.reset()
      this.info = row
      this.subjectName =
        row?.Course?.map(item => {
          return item.name
        }).join() || ''
      this.subject =
        row?.Course?.map(item => {
          return item.subject
        }).join() || ''
      this.province =
        row?.Course?.map(item => {
          return item.province
        }).join() || ''
      this.form.id = row.id
      this.form.contract_no = row.contract_number
      this.open = true
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    },
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          reviewOrder(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.open = false
              this.getList()
              this.form = {}
              this.info = {}
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    allocation(data) {
      this.visible = true
      this.orderId = data?.id
    },
    submitUser(id) {
      assignOrder({
        id: this.orderId,
        enrollment_teacher_id: id
      }).then(res => {
        if (res.code === 200) {
          this.msgSuccess(res.msg)
          this.visible = false
          this.getList()
        } else {
          this.msgError(res.msg)
        }
      })
    },
    cancelUser() {
      this.visible = false
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm('是否确认导出所有参数数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '订单编号',
            '订单名称',
            '科目',
            '适用地区',
            '订单金额',
            '订单返佣',
            '关联上级',
            '订单状态',
            '买家信息',
            '买家号码',
            '教师信息',
            '提交时间'
          ]
          const filterVal = [
            'order_number',
            'name',
            'subject',
            'province',
            'price',
            'commission',
            'customer',
            'status',
            'center',
            'phone',
            'teach',
            'createdAt'
          ]
          const list = this.sysOrderList.map(item => {
            return {
              order_number: item?.order_number,
              name: item?.Course?.[0]?.name,
              subject: item?.subject,
              province: item?.province,
              price: prices(item?.price),
              commission: prices(item?.commission),
              customer: item?.customer ? item?.customer?.recommenders?.name : '',
              status: this.tagStatus(item.status),
              center: item?.customer ? item?.customer?.name : '',
              phone: item?.customer ? item?.customer?.phone : '',
              teach: item?.customer
                ? item?.customer?.teach_recommenders?.username
                : '',
              createdAt: parseTime(item?.createdAt)
            }
          })

          const data = formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '面授订单',
            autoWidth: true, // Optional
            bookType: 'xlsx' // Optional
          })
          this.downloadLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss">
.info-body {
  padding: 0 24px 16px;
}

.box-card {
  .el-row {
    .el-col-5 {
      .el-form-item {
        margin-right: 0;

        .el-form-item__content {
          width: 70%;
        }
      }
    }
  }
}
</style>
